package com.zhaoqi.hr.repository;

import com.zhaoqi.hr.entity.Settlement;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * 结算记录数据访问层
 */
@Repository
public interface SettlementRepository extends JpaRepository<Settlement, Long> {

    /**
     * 根据结算单号查找
     */
    Optional<Settlement> findBySettlementNo(String settlementNo);

    /**
     * 根据合同ID查找结算记录
     */
    List<Settlement> findByContractId(Long contractId);

    /**
     * 根据结算状态查找
     */
    List<Settlement> findByStatus(Settlement.SettlementStatus status);

    /**
     * 查找待结算的记录
     */
    @Query("SELECT s FROM Settlement s WHERE s.status = 'PENDING'")
    List<Settlement> findPendingSettlements();

    /**
     * 根据结算周期查找
     */
    @Query("SELECT s FROM Settlement s WHERE s.settlementPeriodStart >= :startTime AND s.settlementPeriodEnd <= :endTime")
    List<Settlement> findBySettlementPeriod(@Param("startTime") LocalDateTime startTime, 
                                            @Param("endTime") LocalDateTime endTime);

    /**
     * 统计指定时间段内的结算总额
     */
    @Query("SELECT SUM(s.actualPayout) FROM Settlement s WHERE s.status = 'COMPLETED' AND s.paidAt BETWEEN :startTime AND :endTime")
    BigDecimal sumSettlementAmountByPeriod(@Param("startTime") LocalDateTime startTime, 
                                           @Param("endTime") LocalDateTime endTime);

    /**
     * 统计各状态的结算记录数量
     */
    @Query("SELECT s.status, COUNT(s) FROM Settlement s GROUP BY s.status")
    List<Object[]> countByStatus();

    /**
     * 查找结算失败的记录
     */
    @Query("SELECT s FROM Settlement s WHERE s.status = 'FAILED'")
    List<Settlement> findFailedSettlements();
}
